package com.ruoyi.wxorali.controller;
import com.ruoyi.common.domain.R;
import com.ruoyi.common.security.web.BaseRestController;
import com.ruoyi.system.config.SystemConfig;
import com.ruoyi.wxorali.service.AliYunYuYinService;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 易错词前端控制器
 * </p>
 *
 * @author 兮玥
 * @email 190785909@qq.com
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/system/aliyun")
public class AliYunServletController extends BaseRestController {

	private final AliYunYuYinService aliYunYuYinService;
	private File upload;

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
	/**
	 * 导入TXT
	 * @return
	 */
	@PostMapping("/import")
	public R<?> importTxt(@RequestParam("file") MultipartFile multipartFile) {
		if (Objects.isNull(multipartFile) || multipartFile.isEmpty()) {
			return R.fail("当前导入文件不存在");
		}
		JSONArray array = new JSONArray();
		try {
			// 获取文件名
			String name = multipartFile.getOriginalFilename();
			String[] names = name.split("\\\\");
			name = names[names.length - 1];
			// 获取后缀名
			String fileExt = multipartFile.getContentType();
			if (!fileExt.equals("text/plain")) {
				return R.fail("请选择文本文件");
			}
			String resourceRoot = SystemConfig.getUploadDir();

			File nfile = new File(resourceRoot+"/upload/" + name);
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), nfile);
			JSONObject str = aliYunYuYinService.importTxt(nfile);
			if(str.getString("iden").equals("true")) {
				List<String> list = (List<String>) str.get("url");
				List<String> urls = aliYunYuYinService.heBingYuYin(list);
				for (int i = 0; i < urls.size(); i++) {
					JSONObject obj = new JSONObject();
					obj.put("number", i+1);
					obj.put("url",urls.get(i));
					array.add(obj);
				}
				if(array.size() > 0){
					return R.ok(array);
				}else{
					return R.fail("没有文件存在");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("解析错误，信息:" + e.getMessage());
		}
		return R.fail("系统报错，请联系管理员");
	}


}
